package appx.craft.asd.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import appx.craft.asd.R;
import appx.craft.asd.bean.CountryBean;
import appx.craft.asd.bean.ListItems;
import appx.craft.asd.uc.ApplicationTopBar;
import appx.craft.asd.uc.Country_Dialog;
import appx.craft.asd.uc.OnHeadNavigationSelectedListener;
import appx.craft.asd.uc.TermsCondition_Dialog;
import appx.craft.asd.utils.Utility;

// TODO: Auto-generated Javadoc
/**
 * The Class RegistrationActivity.
 */
public class RegistrationActivity extends Activity implements OnHeadNavigationSelectedListener,OnFocusChangeListener,OnTouchListener{
	
	/** The tag. */
	public final String TAG = RegistrationActivity.class.getCanonicalName();
	
	/** The m top bar. */
	ApplicationTopBar mTopBar;
	
	/** The listview_itemlist. */
	ListView listview_itemlist;
	
	/** The m stackofviews. */
	ArrayList<ListItems> mStackofviews=new ArrayList<ListItems>();
	
	/** The m pop up window. */
	Country_Dialog mPopUpWindow;
	
	/** The m terms_pop window. */
	TermsCondition_Dialog mTerms_popWindow;
	
	/** The textview_terms_condition. */
	TextView textview_terms_condition;
	
	/** The layout_liner_panel. */
	View layout_liner_panel;
	
	/** The edittext_email. */
	EditText edittext_country,edittext_mobile_number,edittext_email;
	
	/** The btn_calander_month. */
	Button btn_calander_picker,btn_calander_year,btn_calander_date,btn_calander_month;
	
	/** The edittext_last_name. */
	EditText edittext_fisrt_name,edittext_last_name;
	
	/** The btn_female. */
	Button btn_male,btn_female;
	
	/** The btn_register. */
	Button btn_register;
	
	/** The checkbox_terms. */
	CheckBox checkbox_terms;
	
	/** The edit text temp. */
	private EditText editTextTemp;
	
	/** The p year. */
	int pYear;
	
	/** The p month. */
	int pMonth;
	
	/** The p day. */
	int pDay;
	
	/** The index. */
	int index;
	
	/** The is prevent del. */
	boolean isPreventDel = false;
	
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG,"[ onCreate ] ");
		setContentView(R.layout.activity_registration);
		mTopBar = (ApplicationTopBar)findViewById(R.id.top_bar_application);
		mTopBar.setTitle(getResources().getString(R.string.activity_registration));
		mTopBar.setOnTouchListener(this);
		mPopUpWindow = new Country_Dialog(RegistrationActivity.this);
		mTerms_popWindow = new  TermsCondition_Dialog(RegistrationActivity.this);
		
		edittext_fisrt_name = (EditText)findViewById(R.id.edittext_fisrt_name);
		edittext_fisrt_name.setOnFocusChangeListener(this);
		edittext_last_name = (EditText)findViewById(R.id.edittext_last_name);
		edittext_last_name.setOnFocusChangeListener(this);
		
		edittext_email = (EditText)findViewById(R.id.edittext_email);
		edittext_email.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				editTextTemp =(EditText)v;
				if(!hasFocus){
					
					if(edittext_email.getText().toString().length()>0){
						
						if(!Utility.checkEmail(edittext_email.getText().toString().trim())){
							showAlertEmailError("Email validation error","Invalid Email Address!!");
						}
						
					}else{
						
						showAlertEmailError("Email validation error","Please enter email address!!");
						
					}
				}
			}
		});
		edittext_country = (EditText)findViewById(R.id.edittext_country);
		edittext_country.setOnFocusChangeListener(this);
		edittext_country.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mPopUpWindow.showDialog();
			}
		});
		
		edittext_mobile_number = (EditText)findViewById(R.id.edittext_mobile_number);
		edittext_mobile_number.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				
				if (keyCode==KeyEvent.KEYCODE_DEL) 
		        {
					Log.d(TAG,"[ Pressed Dele ] " + isPreventDel);
					if(isPreventDel){
						return true;	
					}{
						return false;
					}
		            
		        }
				
				return false;
			}
		});
		edittext_mobile_number.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			
			@Override
			public void afterTextChanged(Editable s) {
				
				 index = s.length();
				 Log.d(TAG,"[ INDEX] "+index);
				 
				if(index == 10){
					if(edittext_country.getTag() != null){
						
						CountryBean mBean =(CountryBean) edittext_country.getTag();
						int checkLength = mBean.getCode().length();
						char[] mCompare = new char[checkLength];
						s.getChars(0,checkLength,mCompare,0);
						String strFindChar = new String(mCompare);
						Log.d(TAG,"[Find]"+ strFindChar);
						if(!mBean.getCode().equalsIgnoreCase(strFindChar)){
							s.insert(0,mBean.getCode(),0, mBean.getCode().length());	
						}
					}
				 }else{
					 
					 if(edittext_country.getTag() != null){
						CountryBean mBean =(CountryBean) edittext_country.getTag();
						int checkLength = mBean.getCode().length();
						Log.d(TAG,"[CODE LENGTH]" + checkLength + "[ CODE ]" + mBean.getCode());
						 if(index == checkLength){
							 char[] mCompare = new char[checkLength];
							 s.getChars(0,checkLength,mCompare,0);
							 String strFindChar = new String(mCompare);
							 if(mBean.getCode().equalsIgnoreCase(strFindChar)){
									isPreventDel = true;
							}	 
						 }else{
								isPreventDel = false;
						 }
							 
						
					}
				 }
					
			}
			
		});
		edittext_mobile_number.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
					if(edittext_country.getTag() == null){
						showAlertEmailError("Alert : Mobile Number","Please select country");
					}
				}
			}
		});
		
		btn_calander_picker = (Button)findViewById(R.id.btn_calander_picker);
		btn_calander_picker.setOnClickListener(new OnClickListener() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		
		btn_calander_year = (Button)findViewById(R.id.btn_calander_year);
		btn_calander_date = (Button)findViewById(R.id.btn_calander_date);
		btn_calander_month = (Button)findViewById(R.id.btn_calander_month);
		
		/** Get the current date */
        final Calendar cal = Calendar.getInstance();
        pYear = cal.get(Calendar.YEAR);
        pMonth = cal.get(Calendar.MONTH);
        pDay = cal.get(Calendar.DAY_OF_MONTH);
 
        /** Display the current date in the TextView */
        updateDisplay();
        
        
        textview_terms_condition = (TextView)findViewById(R.id.textview_terms_condition);
        textview_terms_condition.setClickable(false);
        Pattern pattern = Pattern.compile("Terms and Conditions");
        Linkify.addLinks(textview_terms_condition,pattern,"https://");
        
        layout_liner_panel = (View)findViewById(R.id.layout_liner_panel);
        layout_liner_panel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mTerms_popWindow.show();
			}
		});
    
        btn_male = (Button)findViewById(R.id.btn_male);
        btn_male.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				btn_male.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_blue));
				btn_female.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_grey));
			}
		});
        btn_female = (Button)findViewById(R.id.btn_female);
        btn_female.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				btn_male.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_grey));
				btn_female.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_blue));
			}
		});
        
        
    	btn_male.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_blue));
		btn_female.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_grey));
        
		
		btn_register = (Button)findViewById(R.id.btn_register);
		btn_register.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(Utility.checkEmail(edittext_email.getText().toString().trim())){
					
				}
			}
		});
		
		checkbox_terms = (CheckBox)findViewById(R.id.checkbox_terms);
		checkbox_terms.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
				
				}
			}
		});
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG,"[ onStart ] ");
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG,"[ onStop ] ");
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG,"[ onPause ] ");
		hideKeyBoard();
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG,"[ onResume ] ");
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG,"[ onDestroy ] ");
		if(mPopUpWindow != null){
			mPopUpWindow.dismiss();
		}
		if(mTerms_popWindow != null){
			mTerms_popWindow.dismiss();
		}
	}

	/* (non-Javadoc)
	 * @see appx.craft.asd.uc.OnHeadNavigationSelectedListener#onButtonSelected(appx.craft.asd.bean.CountryBean)
	 */
	@Override
	public void onButtonSelected(CountryBean tag) {
		isPreventDel = true;
		if(edittext_country.getTag() != null){
			
			if(edittext_mobile_number.getText().length()>0){
				
				CountryBean oldBean = (CountryBean)edittext_country.getTag();
				Log.d(TAG,"[old code Find]"+ oldBean.getCode());
				int checkLength = tag.getCode().length();
				char[] mCompare = new char[checkLength];
				tag.getCode().getChars(0,checkLength,mCompare,0);
				String strFindChar = new String(mCompare);
				Log.d(TAG,"[New code Find]"+ strFindChar);
				if(!oldBean.getCode().equalsIgnoreCase(strFindChar)){
					Log.d(TAG,"[ ***** TAG  ***** ]"+ tag.getCode());
					edittext_country.setTag(tag);
					edittext_mobile_number.getText().replace(0,oldBean.getCode().length(),tag.getCode());
				}else{
					edittext_mobile_number.getText().insert(0,tag.getCode());
				}	
			}else{
				edittext_mobile_number.setText(tag.getCode());
			}
			
		}else{
			edittext_mobile_number.setText(tag.getCode());
		}
		
		edittext_country.setTag(tag);
		StringBuilder mBuilder = new StringBuilder();
		mBuilder.append("(").append(tag.getCode()).append(")").append(tag.getName());
		edittext_country.setText(mBuilder.toString());
		
		
		if(mPopUpWindow != null){
			mPopUpWindow.closeDialog();
		}
		
	}
	
	/**
	 * Append code.
	 *
	 * @param mCode the m code
	 */
	public void appendCode(String mCode){
		
		StringBuilder mCompleteNumber = new StringBuilder();
		mCompleteNumber.append(mCode);// first add country code
		mCompleteNumber.append(edittext_mobile_number.getText().toString().trim()); // then mobile number
		edittext_mobile_number.setText(null);
		
//		edittext_mobile_number.getText().replace(Math.min(selectionStart, selectionEnd), Math.max(selectionStart, selectionEnd),mCompleteNumber, 0, mCompleteNumber.length());
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		 switch (id) {
	        case DATE_DIALOG_ID:
	            return new DatePickerDialog(RegistrationActivity.this, 
	                        pDateSetListener,
	                        pYear, pMonth, pDay);
	        }
	   return null;
		
	}
	
	 /** This integer will uniquely define the dialog to be used for displaying date picker.*/
    static final int DATE_DIALOG_ID = 0;
     
    /** Callback received when the user "picks" a date in the dialog. */
    private DatePickerDialog.OnDateSetListener pDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
 
                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    pYear = year;
                    pMonth = monthOfYear;
                    pDay = dayOfMonth;
                    updateDisplay();
                }
            };
     
    /**
     * Updates the date in the button.
     */
    private void updateDisplay() {
		new StringBuilder()
				// Month is 0 based so add 1
				.append(pMonth + 1).append("/").append(pDay).append("/")
				.append(pYear).append(" ");
		btn_calander_month.setText(String.valueOf(pMonth + 1));
		btn_calander_date.setText(String.valueOf(pDay));
		btn_calander_year.setText(String.valueOf(pYear));
    }
    
	/**
	 * Hide key board.
	 *
	 * @param editTextTemp the edit text temp
	 */
	public void hideKeyBoard(EditText editTextTemp){
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		if(editTextTemp != null){
			imm.hideSoftInputFromWindow(editTextTemp.getWindowToken(), 0);
		}
		
	}
	
	/**
	 * Show alert email error.
	 *
	 * @param titile the titile
	 * @param mssage the mssage
	 */
	public void showAlertEmailError(String titile,String mssage){
		
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(RegistrationActivity.this);
		// Setting Dialog Title
		alertDialog.setTitle(titile);

		// Setting Dialog Message
		alertDialog.setMessage(mssage);

		// Setting Icon to Dialog
		alertDialog.setIcon(android.R.drawable.ic_dialog_alert);

	    alertDialog.setPositiveButton("OK",new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				hideKeyBoard();
				dialog.dismiss();
				
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnFocusChangeListener#onFocusChange(android.view.View, boolean)
	 */
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if(hasFocus)
		editTextTemp = (EditText)v;
		
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
	 */
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		if(editTextTemp != null)
		imm.hideSoftInputFromWindow(editTextTemp.getWindowToken(), 0);
		return false;
	}
	
	public void hideKeyBoard(){
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		if(editTextTemp != null){
			imm.hideSoftInputFromWindow(editTextTemp.getWindowToken(), 0);
		}
	}
	
}
